#include <unistd.h>
#include <stdio.h>
#include <assert.h>

// 子进程间获取对方的进程号

int main()
{
	int pfd[2]; // 0 for read, 1 for write
	pipe(pfd);

	pid_t son1_pid = fork();
	if (son1_pid)
	{
		// i'm father, i know son1_pid
		pid_t son2_pid = fork();
		if (son2_pid)
		{
			return 0;
		}
		else  // i'm son2, i know son1_pid too
		{
			close(pfd[0]);
			son2_pid = getpid();
			write(pfd[1], &son2_pid, sizeof(son2_pid));

			//printf("[son2]pfd: %d\n", pfd[1]);
			printf("[son2]i'm: %d, your pid: %d\n", son2_pid, son1_pid);

			close(pfd[1]);
		}
	}
	else   // i'm son1, i don't know son2_pid
	{
		close(pfd[1]);

		char ch;
		int i = 0;
		char buf[256];
		while (read(pfd[0], &ch, 1) > 0)
			buf[i++] = ch;

		assert(i == sizeof(pid_t));

		//printf("[son1]pfd: %d\n", pfd[0]);
		printf("[son1]i'm: %d, your pid: %d\n", getpid(), *(pid_t*)buf);
		close(pfd[0]);
	}

	return 0;
}
